package com.cdhkppm.service.impl;

import com.cdhkppm.dto.SwitchExecutersDTO;
import com.cdhkppm.mapper.SwitchExecutersMapper;
import com.cdhkppm.service.SwitchExecutersService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.hustcad.plm.pdm.core.handle.exception.SystemErrorCodeEnum;
import com.hustcad.plm.rpm.model.dto.job.JobStatusUpdateDTO;
import com.hustcad.plm.rpm.model.entity.job.TyppmJob;
import com.hustcad.plm.rpm.model.vo.recent.TyppmOperationRecordVO;
import com.hustcad.plm.rpm.service.job.TyppmJobService;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Description xxx
 *
 * @auther: xxx
 * @date: xxx
 */
@Slf4j
@Service

public  class SwitchExecutersServiceImpl implements SwitchExecutersService {
    @Resource
    private TyppmJobService typpmJobService;
    @Resource
    private SwitchExecutersMapper switchExecutersMapper;
    /**
     * 将任务转交给新执行人：退回 -> 更新执行人 -> 下达
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void transferToTheExecutor(List<SwitchExecutersDTO> switchExecutersDTO) {
        if (switchExecutersDTO == null || switchExecutersDTO.isEmpty()) {
            return;
        }

        // 1. 提取所有 jobId，用于批量操作
        List<String> oids = switchExecutersDTO.stream()
                .map(SwitchExecutersDTO::getJobId)
                .collect(Collectors.toList());

        // 2. 获取统一的 replacementOID（使用第一个任务的，或可改为每个任务独立处理）
        String replacementOID = switchExecutersDTO.get(0).getReplacementOID();

        // === 步骤1：批量“退回”所有任务 ===
        batchUpdateJobStatus(switchExecutersDTO, "已退回", "退回");

        // === 步骤2：批量更新执行人（executorOID）===
        switchExecutersMapper.batchUpdateJobs(oids, replacementOID, null, null);

        // === 步骤3：批量更新状态为“未读”（仅当原状态为“已接收”）===
        switchExecutersMapper.batchUpdateJobs(oids, null, "未读", "已接收");


        // 假设所有任务的 containerOID 相同（或取第一个）
        String containerOID = switchExecutersDTO.get(0).getContainerOID();

        List<String> jobIds = switchExecutersDTO.stream()
                .map(SwitchExecutersDTO::getJobId)
                .collect(Collectors.toList());

        switchExecutersMapper.batchUpdateExecutorOID(containerOID, replacementOID, jobIds);
        // === 步骤4：对每个任务执行“下达”前检查并设置状态 ===
        // 注意：这里无法完全批量，因为要检查父任务状态
        for (SwitchExecutersDTO dto : switchExecutersDTO) {
            handleJobDelivery(dto);
        }
    }

    /**
     * 批量更新任务状态（退回）
     */
    private void batchUpdateJobStatus(List<SwitchExecutersDTO> dtos, String newState, String passName) {
        dtos.forEach(dto -> {
            JobStatusUpdateDTO jobStatusUpdateDTO = new JobStatusUpdateDTO();
            jobStatusUpdateDTO.setJobId(dto.getJobId());

            TyppmOperationRecordVO operationRecordVO = new TyppmOperationRecordVO();
            operationRecordVO.setPassname(passName);
            operationRecordVO.setRemark(dto.getBounceMessages());
            jobStatusUpdateDTO.setOperationRecordVO(operationRecordVO);

            typpmJobService.setJobState(jobStatusUpdateDTO, newState);
        });
    }

    /**
     * 处理单个任务的“下达”逻辑（含父任务检查）
     */
    private void handleJobDelivery(SwitchExecutersDTO dto) {
        JobStatusUpdateDTO jobStatusUpdateDTO = new JobStatusUpdateDTO();
        jobStatusUpdateDTO.setJobId(dto.getJobId());

        TyppmOperationRecordVO operationRecordVO = new TyppmOperationRecordVO();
        operationRecordVO.setPassname("下达");
        operationRecordVO.setRemark(dto.getBounceMessages());
        jobStatusUpdateDTO.setOperationRecordVO(operationRecordVO);

        // 查询当前任务
        TyppmJob job = typpmJobService.selectOneByOID(dto.getJobId());
        if (job == null) {
            throw new IllegalArgumentException("任务不存在: " + dto.getJobId());
        }

        // 检查父任务状态
        String parentOID = job.getParentOID();
        if (StringUtils.isNotBlank(parentOID)) {
            TyppmJob parentJob = typpmJobService.selectOneByOID(parentOID);
            if (parentJob != null && "未下达".equals(parentJob.getState())) {
                throw SystemErrorCodeEnum.NOT_GIVE.message(new Object[]{parentJob.getName()});
            }
        }

        // 设置任务状态为“未读”（代表已下达）
        typpmJobService.setJobState(jobStatusUpdateDTO, "未读");
    }

}

